import React,{ Component } from 'react'
import {
    LegionsProForm,
    LegionsProModal,
    LegionsProDragger,
} from 'legions-pro-design';
import { OpenConfirm } from 'legions-lunar/antd-toolkit';
import {
    Row,
    Icon,
    Dropdown,
    Menu,
    message,
    Button,
} from 'antd';
import { InstanceProForm,IGroup } from 'legions-pro-design/es/LegionsProForm/interface';
import { InstanceProModal } from 'legions-pro-design/es/LegionsProModal/interface';
import { InstanceProTable } from 'legions-pro-design/es/LegionsProTable/interface';
import { IProConditions } from 'legions-pro-design/es/LegionsProConditions/ProConditionsUtils';
import { bind,observer } from 'legions/store-react'
import ProjectStore from '../../stores/projectStore';
import classNames from 'classnames';
import { observable,action,computed,runInAction } from 'mobx';
import { observablePromise } from 'legions/store-utils'
import styles from '../../assets/css/form-page.modules.less'
import FormProerty from '../components.property/formProperty';
import { PropertyFormElementFormFields } from '../../models/form/propertyFormElement';
import { ComponentType, IPropertyValue } from '../../stores/projectFormProperty';
import { PropertyInputVModel,PropertySelectVModel,PropertyDatePickerVModel,PropertyRangePickerVModel,PropertyUploadVModel,PropertySwitchVModel,PropertyRadioButtonVModel } from '../../models/propertyVModel';
import { MapperEntity } from 'json-mapper-object';
import { I_FORM_PROPS,FORMSUBMITPROPERTY } from '../../constants/consts';
import { cloneDeep } from 'lodash'
import CodeEditor from '../../components/codeEditor';
import { transformValidationRule } from '../../utils/form-page-codemod';
import { getExecutableScript } from '../../utils/codemodCore';
import { HlLabeledValue } from 'legions-lunar/model';
import get from 'lodash/get'
import { lazyInject } from 'legions-control-container';
import { FormCanvasDomain } from '../../services/components/formCanvasDomain';
import {toJS} from 'mobx'
type IQuery=Array<IProConditions['componentModel']>
interface IProps {
    store?: ProjectStore
}
const FORM_BASE_DATA = {
    text: {
        name: '文本框',
    },
    select: {
        name: '下拉列表'
    },
    radioButton: {
        name: '单选组合'
    },
    radio: {
        name: '单选组合'
    },
    date: {
        name: '日期',
    },
    daterange: {
        name: '日期范围',
    },
    upload: {
        name: '上传',
    },
    switch: {
        name: '开关',
    }
}
const valueEnum = { '1': 'expression','2': 'expression','3': 'function' }
@bind({ store: ProjectStore })
@observer
export default class FormInformationCanvas extends Component<IProps,{}> {
    /** 表单领域方法 */
    @lazyInject(FormCanvasDomain)
    formCanvasDomain!: FormCanvasDomain

    @computed get group() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        return formPropertyApp.propertyFormationVM.group;
    }
    constructor(props: IProps) {
        super(props)
        this.state = {

        }
    }

    get getFormComponentPropertyViewModel() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        if (!formPropertyApp.formProperyCommonRef) {
            return null;
        }
        const InputDataModel: PropertyFormElementFormFields = formPropertyApp.formProperyCommonRef.viewModel.InputDataModel as PropertyFormElementFormFields
        return InputDataModel
    }
    newViewModel = (props) => {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        return { ...formPropertyApp.formDraggerModel,...props }
    }
    render() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        const { propertyType,property } = formPropertyApp.propertyFormationVM.editComponentData
        const value = formPropertyApp.getProperyElementValue(property) as HlLabeledValue;
        const codes = formPropertyApp.propertyFormationVM.getPropertyValueTemp(property,valueEnum[value?.key] || propertyType)
        let code = '';
        if (codes) {
            code = codes.value as string
            formPropertyApp.propertyFormationVM.codeValue = code;
        }
        return (
            <React.Fragment>
                <div style={{ display: `${formPropertyApp.propertyFormationVM.propertyData.size ? 'block' : 'none'}` }}>
                <LegionsProForm
                        mapPropsToFields={(props) => {
                            const obj = {}
                            Object.keys(props).forEach((item) => {
                                obj[item] = {
                                    ...props[item],
                                    value: props[item] && toJS(props[item].value)
                                }
                            })
                            return obj // 实际处理结果实体
                        }}
                        InputDataModel={this.newViewModel}
                        onFieldsChange={(props,formFields) => {
                            formPropertyApp.formPropertyDraggerRef.store.updateFormInputData(formPropertyApp.formPropertyDraggerRef.uid,{...formFields})
                        }}
                        onReady={(form,ref) => {
                            formPropertyApp.formPropertyDraggerRef = Object.assign(ref,{ that: this });
                        }}
                        isDragSort
                        group={this.group}
                        colCount={formPropertyApp.propertyFormationVM.layout}
                        size={formPropertyApp.propertyFormationVM.size}
                        controls={[]}
                    ></LegionsProForm>
                </div>
                {<Row style={{ display: `${formPropertyApp.propertyFormationVM.propertyData.size ? 'none' : 'block'}` }} className={classNames({
                        [styles['FormPageUnSelected']]: true,
                })}><h3>请拖入表单元素组件</h3></Row>}
                 {/*  ======= 表单项属性设置=====start */}
                <LegionsProModal
                        closable={false}
                        maskClosable={false}
                        footer={(<React.Fragment>
                            <Button onClick={() => {
                                OpenConfirm({
                                    title: '关闭',
                                    content: '部分数据未保存,如果离开数据将无法保存,您确定离开吗？',
                                    onOk: () => {
                                        formPropertyApp.formPropertyModalRef.viewModel.visible = false;
                                    }
                                })
                            }}>取消</Button>
                            <Button type="primary" onClick={() => {
                                formPropertyApp.formProperyElementRef.viewModel.form.validateFields((error,values) => {
                                    if (!error) {
                                        const arr: string[] = FORMSUBMITPROPERTY[formPropertyApp.propertyFormationVM.editComponentData.type]
                                        arr.map((item) => {
                                            if (values.hasOwnProperty(item)) {
                                                let oldPropertyType:IPropertyValue['type'] = 'normal';
                                                const oldItem = formPropertyApp.propertyFormationVM.getPropertyValue(item)
                                                
                                                if (oldItem) {
                                                    oldPropertyType = oldItem.type;
                                                }
                                                formPropertyApp.propertyFormationVM.updatePropertyValue({
                                                    value: values[item],
                                                    property: item,
                                                    propertyType: oldPropertyType,
                                                })
                                            }
                                        })
                                        message.success('设置成功');
                                        formPropertyApp.formPropertyModalRef.viewModel.visible = false;
                                    }
                                })
                            }}>保存</Button>
                        </React.Fragment>)}
                        modalType="drawer"
                        placement="right"
                        onReady={(value) => {
                            formPropertyApp.formPropertyModalRef = value;
                            const width = 400;
                            formPropertyApp.formPropertyModalRef.viewModel.width = width;
                    }}>
                    <FormProerty></FormProerty>
                    </LegionsProModal>
                {/*  ======= 表单项属性设置=====end */}
                
               {/*  ======= 代码编辑对话框=====start */}
                <LegionsProModal
                        closable={false}
                        footer={(<React.Fragment>
                            <Button onClick={() => {
                                OpenConfirm({
                                    title: '关闭',
                                    content: '您还未保存输入信息,确定需要离开？',
                                    onOk: () => {
                                        formPropertyApp.formPropertyCodeEditModalRef.viewModel.visible = false;
                                    }
                                })
                            }}>取消</Button>
                            <Button type="primary" onClick={() => {
                                try {
                                    runInAction(() => {
                                        formPropertyApp.propertyFormationVM.execcodeast = null;
                                        const backfillField = ['uploadParams','uploadDataTransform','disabledDate'];// 回填到表单组件属性项
                                        let formFields = null;
                                        backfillField.map((item) => {
                                            if (formFields === null) {
                                                formFields = {};
                                            }
                                            if (formPropertyApp.propertyFormationVM.editComponentData.property === item) {
                                                formFields[item] = {
                                                    value: formPropertyApp.propertyFormationVM.codeValue
                                                }
                                            }
                                        })
                                        if (formFields) {
                                            formPropertyApp.formProperyElementRef.store.updateFormInputData(formPropertyApp.formProperyElementRef.uid,formFields)
                                        }
                                        const mapjson = {
                                            validationRuleReg: transformValidationRule
                                        }
                                        const validationRuleFunction = mapjson[formPropertyApp.propertyFormationVM.editComponentData.property]
                                        if (validationRuleFunction) {
                                            eval(getExecutableScript(validationRuleFunction(formPropertyApp.propertyFormationVM.codeValue,
                                                valueEnum[value.key],
                                                'this.props.store.context.formPropertyApp.propertyFormationVM.execcodeast'
                                            ),this));
                                        }
                                        formPropertyApp.propertyFormationVM.updatePropertyValueTemp({
                                            value: formPropertyApp.propertyFormationVM.codeValue,
                                            property: property,
                                            propertyType: valueEnum[value?.key] || propertyType,
                                        });
                                        formPropertyApp.propertyFormationVM.updatePropertyValue({
                                            value: formPropertyApp.propertyFormationVM.codeValue,
                                            property: property,
                                            propertyType: valueEnum[value?.key] || propertyType,
                                            execast: formPropertyApp.propertyFormationVM.execcodeast,
                                        })
                                        message.success('保存成功');
                                        formPropertyApp.propertyFormationVM.editComponentData.property = null;
                                        formPropertyApp.propertyFormationVM.editComponentData.propertyType = null;
                                        formPropertyApp.formPropertyCodeEditModalRef.viewModel.visible = false;
                                    })
                                } catch (error) {
                                    console.log(error)
                                    message.warning('error.message',4)
                                }

                            }}>保存</Button>
                        </React.Fragment>)}
                        maskClosable={false}
                        onReady={(value) => {
                            formPropertyApp.formPropertyCodeEditModalRef = value;
                            const width = 600;
                            formPropertyApp.formPropertyCodeEditModalRef.viewModel.width = width;
                        }}
                    >
                        <CodeEditor
                            width="100%"
                            height="300px"
                            mode="typescript"
                            value={code}
                            tabSize={4}
                            onChange={(values: string,evet) => {
                                formPropertyApp.propertyFormationVM.codeValue = values;
                                console.log(formPropertyApp.propertyFormationVM.codeValue)
                            }}
                        ></CodeEditor>
                </LegionsProModal>
                {/*  ======= 代码编辑对话框=====end */}
            </React.Fragment>
        )
    }
}